package com.newlink.building.userinfo.activity

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.mlkit.vision.barcode.common.Barcode
import com.king.mlkit.vision.barcode.BarcodeDecoder
import com.newlink.building.common_base.base.NL_BaseActivity
import com.newlink.building.common_base.base.BaseFragment
import com.newlink.building.common_base.model.bean.MessageListArrayData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.RegexUtils
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.adapter.Module_UserInfo_ViewPagerAdapter
import com.newlink.building.userinfo.databinding.ActivityDeviceMacScanBinding
import com.newlink.building.userinfo.fragment.Module_UserInfo_BarCodeScanFragment
import com.newlink.building.userinfo.fragment.Module_UserInfo_QrCodeScanFragment

/**
 * Created by xiaodong on 2025/1/15.
 */
class Module_UserInfo_DeviceMacScanActivityNL : NL_BaseActivity() {

    private var curList: MutableList<MessageListArrayData> = ArrayList()
    private var mAdapter: Module_UserInfo_ViewPagerAdapter? = null
    private lateinit var mQrCodeScanFragment: Module_UserInfo_QrCodeScanFragment
    private lateinit var mBarCodeScanFragment: Module_UserInfo_BarCodeScanFragment

    companion object {
        const val REQUEST_QR_PICK_IMAGE = 1001
        const val REQUEST_BAR_PICK_IMAGE = 1002
    }

    private lateinit var mBinding: ActivityDeviceMacScanBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityDeviceMacScanBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun allowFontScale() = false

    override fun initColor() {
        super.initColor(R.color.black)
    }

    override fun initData() {
        tabArray = mutableListOf(
            getString(R.string.tab_scan_barcode),
            getString(R.string.tab_scan_qrcode),
        )
        val list = mutableListOf<BaseFragment>()
        mQrCodeScanFragment = Module_UserInfo_QrCodeScanFragment()
        mBarCodeScanFragment = Module_UserInfo_BarCodeScanFragment()

        list.add(mBarCodeScanFragment)
        list.add(mQrCodeScanFragment)
        mAdapter = Module_UserInfo_ViewPagerAdapter(supportFragmentManager, lifecycle)
        mAdapter?.setFragments(list)

        mBinding.viewPager.adapter = mAdapter
        mBinding.viewPager.isUserInputEnabled = false

        val curPage = intent.getIntExtra("PAGE", 0)

        TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager) { tab, position ->
            val badge =
                LayoutInflater.from(this).inflate(R.layout.badge_layout, null) as RelativeLayout
            badge.findViewById<TextView>(R.id.contentView).text = tabArray[position]
            tab.customView = badge
            if (position == curPage) {
                tab.customView?.findViewById<TextView>(R.id.contentView)?.setTextColor(
                    ContextCompat.getColor(
                        this@Module_UserInfo_DeviceMacScanActivityNL,
                        R.color.white
                    )
                )
            } else {
                tab.customView?.findViewById<TextView>(R.id.contentView)?.setTextColor(
                    ContextCompat.getColor(
                        this@Module_UserInfo_DeviceMacScanActivityNL,
                        R.color.white_60
                    )
                )
            }
        }.attach()


        mBinding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                val tabTitle = tab.customView?.findViewById<TextView>(R.id.contentView)
                tabTitle?.setTextColor(
                    ContextCompat.getColor(
                        this@Module_UserInfo_DeviceMacScanActivityNL,
                        R.color.white
                    )
                )
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                val tabTitle = tab.customView?.findViewById<TextView>(R.id.contentView)
                tabTitle?.setTextColor(
                    ContextCompat.getColor(
                        this@Module_UserInfo_DeviceMacScanActivityNL,
                        R.color.white_60
                    )
                )
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                // 可选: 处理重新选中 Tab 的逻辑
            }
        })

    }

    override fun initView() {
        window.statusBarColor = Color.BLACK

        val windowInsetsController = ViewCompat.getWindowInsetsController(
            window.decorView
        )
        if (windowInsetsController != null) {
            windowInsetsController.isAppearanceLightStatusBars = false
        }
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.device_add_scan_title)
        mBinding.titleBar.imageTitleBarBack.setOnClickListener {
            finish()
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if ((requestCode == REQUEST_QR_PICK_IMAGE || requestCode == REQUEST_BAR_PICK_IMAGE) && resultCode == RESULT_OK) {
            if (data != null) {
                processPhoto(data?.data, requestCode)
            }
        }
    }

    private fun processPhoto(data: Uri?, requestCode: Int) {
        data?.let {
            try {
                BarcodeDecoder.process(
                    BarcodeDecoder.fromFilePath(this, it),
                    Barcode.FORMAT_ALL_FORMATS
                ).addOnSuccessListener(this) { result ->

                    if (result.isNotEmpty()) {
                        val srcBitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
//                        showResultDialog(srcBitmap, result)
                        val buffer = StringBuilder()
                        for (barcode in result) {
                            barcode.displayValue?.let {
                                if (RegexUtils.checkMac(it)) {
                                    buffer.append(it)
                                }
                            }

                        }
                        val res = buffer.toString()
                        NLog.e("res =========> $res")
                        if (res.isNotEmpty()) {
                            handleQRCode(res, requestCode)
                        } else {
                            showParseQrCodeErrorDialog(requestCode)
                        }
                    } else {
                        NLog.e("result is empty")
                        showParseQrCodeErrorDialog(requestCode)
                    }

                }.addOnFailureListener(this) { e ->
                    // 失败
                    NLog.e("$e")
                    showParseQrCodeErrorDialog(requestCode)
                }
            } catch (e: Exception) {
                NLog.e("$e")
                showParseQrCodeErrorDialog(requestCode)
            }
        }
    }

    private fun showParseQrCodeErrorDialog(requestCode: Int) {
        val message =
            if (requestCode == REQUEST_BAR_PICK_IMAGE) getString(R.string.invalid_bar_code) else getString(
                R.string.invalid_qr_code
            )
        CustomMessageDialog(this).setMessage(message)
            .setNegativeButton(
                resources.getString(R.string.confirm_dialog_custom)
            ) { dialog -> dialog.dismiss() }.setPositiveButton(null).show()
    }

    private fun handleQRCode(qrCodeText: String, resultCode: Int) {
        // 在这里处理识别到的二维码文本，如显示到界面上或进行其他操作
        NLog.e("扫码信息为:${qrCodeText}")
        val bundle = Bundle()
        bundle.putString("data", qrCodeText)
        bundle.putInt("type", if (resultCode == REQUEST_BAR_PICK_IMAGE) 1 else 0)
        setResult(RESULT_OK, intent.putExtras(bundle))
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}